package com.lmwyc.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lmwyc.bean.CardList;
import com.lmwyc.bean.UserSession;
import com.lmwyc.constant.Constant;
import com.lmwyc.core.PunshAllThread;
import com.lmwyc.core.SessionThread;
import com.lmwyc.mapper.ExtDayConfigMapper;
import com.lmwyc.mapper.UserSessionMapper;
import com.lmwyc.service.IAreaService;
import com.lmwyc.service.IPunshService;
import com.lmwyc.util.HttpUtil;
import com.lmwyc.util.MailUtil;
import com.lmwyc.util.Utils;

@Service
@Configurable
@EnableScheduling
public class PunshServiceImpl implements IPunshService {

	private static final Logger logger = LoggerFactory.getLogger(PunshServiceImpl.class);
	
	@Autowired
	private MailUtil mail;

	@Value("${masterEmail.to}")
	private String masterEmail;

	@Value("${masterEmail.invalid.title}")
	private String invalidTitle;

	@Value("${masterEmail.invalid.content}")
	private String invalidContent;

	@Value("${masterEmail.punshFailed.title}")
	private String punshFailedTitle;

	@Value("${masterEmail.punshFailed.content}")
	private String punshFailedContent;
	
	@Autowired
	private IAreaService areaService;

	@Autowired
	private UserSessionMapper userSessionMapper;
	
	@Autowired
	private ExtDayConfigMapper extDayConfigMapper;

	@Override
	public List<UserSession> getUserSessionList() {
		return userSessionMapper.selectList();
	}

	@Scheduled(cron = "0 30 8,21 ? * * ")
	public void punsh() {
		List<UserSession> selectList = userSessionMapper.selectList();
		for (UserSession user : selectList) {
			PunshAllThread thread = new PunshAllThread(user, mail, punshFailedTitle, punshFailedContent);
			thread.setExtDayConfigMapper(this.extDayConfigMapper);
			thread.setAreaService(areaService);
			new Thread(thread, user.getUserName()).start();
			logger.info(user.getUserName() + " 启动打卡进程");
		}
	}
	
	/**
	 * 每天零点30分清理过期的的特殊打卡配置
	 */
	@Scheduled(cron = "0 30 0 ? * * ")
	private void clearCus() {
		extDayConfigMapper.clearCus();
	}
	
	public void punshCus() {
		List<UserSession> selectList = userSessionMapper.selectList();
		for (UserSession user : selectList) {
			user.setRandomDelay(1);
			PunshAllThread thread = new PunshAllThread(user, mail, punshFailedTitle, punshFailedContent);
			thread.setExtDayConfigMapper(this.extDayConfigMapper);
			new Thread(thread, user.getUserName()).start();
			logger.info(user.getUserName() + " 启动打卡进程");
		}
	}

	@Override
	public void setUserSession(String userName, String sessionid, int inuse) {
		userSessionMapper.updateUser(userName, sessionid, inuse);
	}

	/**
	 * 每十分钟执行，防止session过期
	 */
	@Scheduled(cron = "0 0/10 * * * ? ")
	public void timingGetSession() {
		List<UserSession> selectList = userSessionMapper.selectList();
		for (UserSession user : selectList) {
			SessionThread thread = new SessionThread(user, mail, userSessionMapper, invalidTitle, invalidContent);
			new Thread(thread, user.getUserName()).start();
		}
	}

	@Override
	public UserSession getUserInfoByWorkNum(String workNum) {
		UserSession user = userSessionMapper.selectOne(workNum);
		if(user != null) {
			Map<String, Double> map = Utils.getRandomAxes(user.getLatitude(), user.getLongitude());
			user.setLatitude(map.get("latitude"));
			user.setLongitude(map.get("longitude"));
		}
		return user;
	}

	@Override
	public String punshNow(String workNum) {
		UserSession user = userSessionMapper.selectOne(workNum);
		PunshAllThread thread = new PunshAllThread(user, mail, punshFailedTitle, punshFailedContent);
		thread.setAreaService(areaService);
		return thread.execCustom();
	}

	@Override
	public CardList getRecord(String workNum) {
		UserSession user = userSessionMapper.selectOne(workNum);
		try {
			Map<String, String> map = new HashMap<String, String>();
			Calendar c = Calendar.getInstance();
			map.put("year", c.get(Calendar.YEAR) + "");
			map.put("month", (c.get(Calendar.MONTH) + 1) + "");
			String res = HttpUtil.sendPost(Constant.GET_CARD_LIST, map, Constant.encoding, user.getUserSessionId());
			ObjectMapper mapper = new ObjectMapper();
			mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"));
			logger.error(res);
			CardList cardList = mapper.readValue(res, CardList.class);
			return cardList;
		} catch (Exception e) {
			logger.error("用户<"  + user.getUserName() + ">获取打卡记录异常", e);
			throw new RuntimeException(e);
		}
	}
}
